import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Main from '../views/Main.vue'
import GoodsDetail from '../views/GoodsDetail.vue'
import shoppingCar from '../views/ShoppingCar.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Main',
    component: Main
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/goodsDetail/:id',
    name: 'GoodsDetail', 
    component: GoodsDetail
  },
  {
    path: '/shoppingCar',
    name: 'ShoppingCar',
    component: shoppingCar
  }
]

import store from '../store'

const router = new VueRouter({
  mode:"history",//地址后边不会有#，需要注意请看：https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90
  routes
})

router.beforeEach((to, from, next) => {
  // console.log(store.state.isLogin);
  //不需要验证是否登录的页面
  let validation = ['Main','Register']
  if (validation.indexOf(to.name) !== undefined) {
    next()
  }else if (to.name !== 'Login' && !store.state.isLogin) {
    //未登录，直接跳转至登录页面
    next({ name: 'Login' })
  }else{
    //已经登录
    next()
  }
})

export default router
